﻿

using LeaderCCSLaserUI.Models;
using Newtonsoft.Json;
using RestSharp;
using System.Configuration;
using System.Threading.Tasks;

namespace LeaderCCSLaserUI.Services
{
    public class LocalMESService : ILocalMESService
    {
        #region 变量
        private RestClient client;
        #endregion
        #region 功能函数
        public async Task<T?> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Route, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameter != null)
                request.AddParameter("application/json", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            var response = await client.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<T>(response.Content);
            else
                return default;
        }
        public T? Execute<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Route, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameter != null)
                request.AddParameter("application/json", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<T>(response.Content);
            else
                return default;
        }
        #endregion
        #region 构造函数
        public LocalMESService()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ApiUrl"].ConnectionString;
            client = new RestClient(connectionString);
        }
        #endregion

    }
}
